package edu.towson.cosc.cosc455.aloiac1.markdowncompiler;

import edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer;

public class MyLexicalAnalyzer implements LexicalAnalyzer {
	/** The current character */
	private char currentChar;

	@Override
	public void getNextToken() {
		getCharacter();
		
		while (isSpace(currentChar))
			getCharacter();
		
		 /** Tag's enter here */
		if (currentChar == '#') {
			addCharacter();
			
			while (!lookupToken() && currentChar != '#')
				addCharacter();
		}
		 /** Text enters here */
		else {
			while (currentChar != '#') {
				addCharacter();
			}
		}
		Compiler.textFromFile = currentChar + Compiler.textFromFile;
	}
	
	/**
	 * This is method gets the current character from the input file and places it in
	 * the Compiler.token variable.
	 */
	@Override
	public void getCharacter() {
		currentChar = Compiler.textFromFile.charAt(0);
		 /** 
		  * Deletes from textFromFile string one char at a time.
		  * This is used instead of "index" and is useful for declaring if anything is after #END DOCUMENT
		  */
		Compiler.textFromFile = Compiler.textFromFile.substring(1); 
	}
	
	 /**
     * This method adds the current character to the nextToken.
     * Also gets next character
     */
	@Override
	public void addCharacter() {
		Compiler.token = Compiler.token + currentChar;
		getCharacter();
	}
	
	/**
	 * This method checks current character to see if there are any spaces
	 *
	 * @param c the current character
	 * @return true, if is space; otherwise false
	 */
	@Override
	public boolean isSpace(char c) {
		if (c ==' ' || c=='\t' || c=='\n' || c=='\r')
			return true;
		return false;
	}
	
	/**
	 * This method checks to see if the current, possible token is legal in the
	 * defined grammar.
	 *
	 * @return true, if it is a legal token, otherwise false
	 */
	@Override
	public boolean lookupToken() {
		for (int count=0; count<Compiler.markdown.length; count++) { 
			if (Compiler.token.equalsIgnoreCase(Compiler.markdown[count]))
				return true;
		}
		return false;
	}
}
